package com.autorun.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.autorun.server.entity.Apk;
import com.autorun.server.mapper.ApkMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * APK管理服务
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
@Service
public class ApkService {

    @Autowired
    private ApkMapper apkMapper;

    /**
     * 获取APK列表（分页）
     * 
     * @param game 游戏名称
     * @param page 页码
     * @param pageSize 页大小
     * @return APK分页数据
     */
    public Page<Apk> getApkList(String game, int page, int pageSize) {
        QueryWrapper<Apk> queryWrapper = new QueryWrapper<>();
        
        if (game != null && !game.trim().isEmpty()) {
            queryWrapper.eq("game", game);
        }
        
        queryWrapper.orderByDesc("upload_time");
        
        Page<Apk> pageRequest = new Page<>(page, pageSize);
        return apkMapper.selectPage(pageRequest, queryWrapper);
    }

    /**
     * 获取APK详情
     * 
     * @param id APK ID
     * @return APK信息
     */
    public Apk getApkById(Integer id) {
        return apkMapper.selectById(id);
    }

    /**
     * 上传APK文件
     * 
     * @param file 上传的文件
     * @param name APK名称
     * @param game 游戏名称
     * @param versionCode 版本代码
     * @param description 描述
     * @param uploadUserId 上传用户ID
     * @return APK信息
     */
    public Apk uploadApk(MultipartFile file, String name, String game, Integer versionCode, 
                         String description, Integer uploadUserId) throws IOException, NoSuchAlgorithmException {
        
        // 检查版本号是否重复
        Integer count = apkMapper.countByGameAndVersionCode(game, versionCode);
        if (count > 0) {
            throw new RuntimeException("该游戏的版本号已存在");
        }
        
        // 计算文件MD5
        String md5Hash = calculateMD5(file.getBytes());
        
        // 这里应该上传到OSS，暂时先保存文件信息
        // TODO: 实现OSS上传逻辑
        String ossPath = "apk/" + game + "/" + file.getOriginalFilename();
        
        // 创建APK记录
        Apk apk = new Apk();
        apk.setName(name);
        apk.setGame(game);
        apk.setVersion(extractVersion(versionCode));
        apk.setVersionCode(versionCode);
        apk.setDescription(description);
        apk.setFileName(file.getOriginalFilename());
        apk.setFileSize(file.getSize());
        apk.setMd5Hash(md5Hash);
        apk.setOssPath(ossPath);
        apk.setUploadUserId(uploadUserId);
        apk.setUploadTime(LocalDateTime.now());
        apk.setIsActive(true);
        apk.setCreateTime(LocalDateTime.now());
        apk.setUpdateTime(LocalDateTime.now());
        
        apkMapper.insert(apk);
        return apk;
    }

    /**
     * 更新APK信息
     * 
     * @param id APK ID
     * @param name APK名称
     * @param description 描述
     * @return APK信息
     */
    public Apk updateApk(Integer id, String name, String description) {
        Apk apk = apkMapper.selectById(id);
        if (apk == null) {
            throw new RuntimeException("APK不存在");
        }
        
        apk.setName(name);
        apk.setDescription(description);
        apk.setUpdateTime(LocalDateTime.now());
        
        apkMapper.updateById(apk);
        return apk;
    }

    /**
     * 切换APK状态
     * 
     * @param id APK ID
     * @param isActive 是否激活
     * @return APK信息
     */
    public Apk toggleApkStatus(Integer id, Boolean isActive) {
        Apk apk = apkMapper.selectById(id);
        if (apk == null) {
            throw new RuntimeException("APK不存在");
        }
        
        apk.setIsActive(isActive);
        apk.setUpdateTime(LocalDateTime.now());
        
        apkMapper.updateById(apk);
        return apk;
    }

    /**
     * 删除APK
     * 
     * @param id APK ID
     */
    public void deleteApk(Integer id) {
        Apk apk = apkMapper.selectById(id);
        if (apk == null) {
            throw new RuntimeException("APK不存在");
        }
        
        // TODO: 删除OSS文件
        
        apkMapper.deleteById(id);
    }

    /**
     * 获取最新的激活APK
     * 
     * @param game 游戏名称
     * @return APK信息
     */
    public Apk getLatestApk(String game) {
        if (game != null && !game.trim().isEmpty()) {
            return apkMapper.findLatestByGame(game);
        } else {
            return apkMapper.findLatest();
        }
    }

    /**
     * 获取APK下载地址
     * 
     * @param id APK ID
     * @return 下载地址
     */
    public String getDownloadUrl(Integer id) {
        Apk apk = apkMapper.selectById(id);
        if (apk == null) {
            throw new RuntimeException("APK不存在");
        }
        
        // TODO: 生成OSS下载地址
        return "http://localhost:8891/api/apks/" + id + "/download";
    }

    /**
     * 计算文件MD5
     * 
     * @param data 文件数据
     * @return MD5哈希值
     */
    private String calculateMD5(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(data);
        
        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     * 从版本代码提取版本字符串
     * 
     * @param versionCode 版本代码
     * @return 版本字符串
     */
    private String extractVersion(Integer versionCode) {
        // 简单的版本号生成逻辑，可以根据实际需求调整
        int major = versionCode / 10000;
        int minor = (versionCode % 10000) / 100;
        int patch = versionCode % 100;
        return String.format("%d.%d.%d", major, minor, patch);
    }
}